package com.example.controller;

import com.example.common.response.Result;
import com.example.model.dto.NoteDTO;
import com.example.model.dto.PageDTO;
import com.example.model.dto.UserProfileDTO;
import com.example.model.entity.Post;
import com.example.model.entity.User;
import com.example.service.PostService;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;
    
    @Autowired
    private PostService postService;

    // 保留原有的用户信息接口
    @GetMapping("/profile")
    public Result<UserProfileDTO> getUserProfile() {
        return Result.success(userService.getUserProfile());
    }

    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        return Result.success(userService.register(user));
    }

    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        return Result.success(userService.findById(id));
    }

    @PutMapping("/{id}")
    public Result<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        return Result.success(userService.updateUser(id, user));
    }

    // 添加新的笔记查询接口
    @GetMapping("/notes")
    public Result<PageDTO<NoteDTO>> getUserNotes(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "12") Integer pageSize) {
        // 获取当前用户ID（这里需要从SecurityContext中获取）
        Long userId = getCurrentUserId();
        
        // 查询分页数据
        Page<Post> postPage = postService.findByUserIdWithPage(userId, PageRequest.of(page - 1, pageSize));
        
        // 转换为DTO
        List<NoteDTO> noteDTOs = postPage.getContent().stream()
                .map(this::convertToNoteDTO)
                .collect(Collectors.toList());
        
        // 构建分页响应
        PageDTO<NoteDTO> pageDTO = new PageDTO<>();
        pageDTO.setRecords(noteDTOs);
        pageDTO.setTotal(postPage.getTotalElements());
        pageDTO.setSize(pageSize);
        pageDTO.setCurrent(page);
        
        return Result.success(pageDTO);
    }

    private NoteDTO convertToNoteDTO(Post post) {
        NoteDTO noteDTO = new NoteDTO();
        noteDTO.setId(post.getId());
        noteDTO.setTitle(post.getTitle());
        noteDTO.setCoverImage(post.getImageUrls()); // 假设第一张图片为封面
        noteDTO.setCreateTime(post.getCreatedAt());
        
        // 获取点赞、评论和收藏数
        noteDTO.setLikes(postService.getLikesCount(post.getId()));
        noteDTO.setComments(postService.getCommentsCount(post.getId()));
        noteDTO.setCollects(postService.getCollectsCount(post.getId()));
        
        return noteDTO;
    }

    private Long getCurrentUserId() {
        // 从SecurityContext中获取当前用户ID的实现
        // 这里需要根据你的认证实现来获取
        return 1L; // 临时返回固定值
    }

    // 获取用户收藏的帖子
    @GetMapping("/collections/notes")
    public Result<PageDTO<NoteDTO>> getUserCollectionNotes(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "12") Integer pageSize) {
        System.out.println("Accessing collections/notes endpoint"); // 添加调试信息
        Long userId = getCurrentUserId();
        System.out.println("UserId: " + userId); // 添加调试信息
        
        Page<Post> postPage = postService.findUserCollections(userId, PageRequest.of(page - 1, pageSize));
        
        List<NoteDTO> noteDTOs = postPage.getContent().stream()
                .map(this::convertToNoteDTO)
                .collect(Collectors.toList());
        
        PageDTO<NoteDTO> pageDTO = new PageDTO<>();
        pageDTO.setRecords(noteDTOs);
        pageDTO.setTotal(postPage.getTotalElements());
        pageDTO.setSize(pageSize);
        pageDTO.setCurrent(page);
        
        return Result.success(pageDTO);
    }

    // 获取用户点赞的帖子
    @GetMapping("/likes/notes")
    public Result<PageDTO<NoteDTO>> getUserLikedNotes(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "12") Integer pageSize) {
        Long userId = getCurrentUserId();
        Page<Post> postPage = postService.findUserLikedPosts(userId, PageRequest.of(page - 1, pageSize));
        
        List<NoteDTO> noteDTOs = postPage.getContent().stream()
                .map(this::convertToNoteDTO)
                .collect(Collectors.toList());
        
        PageDTO<NoteDTO> pageDTO = new PageDTO<>();
        pageDTO.setRecords(noteDTOs);
        pageDTO.setTotal(postPage.getTotalElements());
        pageDTO.setSize(pageSize);
        pageDTO.setCurrent(page);
        
        return Result.success(pageDTO);
    }
} 